package ar.edu.unlam.tpfinal.struts.actions.client;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import ar.edu.unlam.tpfinal.service.ClientService;
import ar.edu.unlam.tpfinal.service.exceptions.ServiceException;
import ar.edu.unlam.tpfinal.struts.exceptions.PresentationException;
import ar.edu.unlam.tpfinal.struts.forms.AddressForm;
import ar.edu.unlam.tpfinal.struts.forms.ClientAddressForm;
import ar.edu.unlam.tpfinal.struts.forms.ClientForm;

public class EditClientPopulateAction extends BaseClientAction {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
							     HttpServletRequest request, HttpServletResponse response) 
			throws Exception {
		
		logger.debug("Inside EditClientPopulateAction");
		
		// Obtener servicio del contexto mediante Spring
		logger.debug("Getting service from context");
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		ClientService clientService = (ClientService) context.getBean("clientService");
		
		// Casteamos el formulario
		ClientAddressForm clientAddressForm = (ClientAddressForm) form;
		
		// Y lo adaptamos
		ClientForm clientForm = clientAddressForm.getClient();
		List<AddressForm> addressFormList = clientAddressForm.getAddressList();
		
		// Buscamos en la BD por el OID
		try {
			clientForm = clientService.getClient(clientForm.getOid());
			addressFormList = clientService.getAllAddressesFromClient(clientForm.getOid());
		} catch(ServiceException ex) {
			throw new PresentationException(ex);
		}
		
		clientAddressForm.setClient(clientForm);
		clientAddressForm.setAddressList(addressFormList);
		
		// Y seguimos camino
		return mapping.findForward("success");
	}
}